﻿using System.Collections.ObjectModel;
using System.Linq;

namespace SharePhone.Core.UserProfile
{
    public class UserProfile
    {
        public string DisplayName
        {
            get
            {
                return
                    GetPropertyValue(
                        (from property in Properties where property.Name == "PreferredName" select property).
                            FirstOrDefault());
            }
            set { UpdateSingleValueProperty("PreferredName", value); }
        }

        public string Picture
        {
            get
            {
                return
                    GetPropertyValue(
                        (from property in Properties where property.Name == "PictureURL" select property).FirstOrDefault
                            ());
            }
        }

        public string Title
        {
            get
            {
                return
                    GetPropertyValue(
                        (from property in Properties where property.Name == "Title" select property).FirstOrDefault());
            }
            set { UpdateSingleValueProperty("Title", value); }
        }

        public string AccountName
        {
            get
            {
                return
                    GetPropertyValue(
                        (from property in Properties where property.Name == "AccountName" select property).
                            FirstOrDefault());
            }
        }

        public ObservableCollection<PropertyData> Properties { get; internal set; }

        private string GetPropertyValue(PropertyData property)
        {
            if (property != null)
            {
                if (property.Values.Count > 0)
                    return property.Values[0].Value as string;
            }
            return string.Empty;
        }

        public void UpdateSingleValueProperty(string propertyName, object value)
        {
            PropertyData prop =
                (from property in Properties where property.Name == propertyName select property).FirstOrDefault();
            if (prop.Values.Count > 0)
            {
                prop.Values[0].Value = value;
            }
            else
            {
                prop.Values.Add(new ValueData {Value = value});
            }
            prop.IsValueChanged = true;
        }
    }
}